import os
import sys
import glob

def formatear_linea(offset, longitud, etiqueta):
    return f"{str(offset).ljust(8)}{str(longitud).ljust(8)}{etiqueta.ljust(20)}\n"

def procesar_archivos(base_name):
    base_path = os.path.dirname(base_name)
    base_file = os.path.basename(base_name)

    bin_files = sorted(glob.glob(os.path.join(base_path, f"{base_file}*.bin")))
    bin_files = [f for f in bin_files if os.path.basename(f) != f"{base_file}.bin"]

    primera_secciones = []
    segunda_secciones = []

    log_lines = [f"Procesando archivos con base: {base_name}\n"]
    log_lines.append(f"Archivos encontrados: {bin_files}\n")

    for bin_file in bin_files:
        nombre_sin_ext = os.path.splitext(bin_file)[0]
        txt_file = nombre_sin_ext + ".txt"

        try:
            with open(txt_file, "r", encoding="utf-8") as f:
                lines = f.readlines()
                offset1, length1 = map(int, lines[1].split()[:2])
                offset2, length2 = map(int, lines[2].split()[:2])

            with open(bin_file, "rb") as f:
                data = f.read()

            primera_secciones.append(data[offset1:offset1+length1])
            segunda_secciones.append(data[offset2:offset2+length2])

            log_lines.append(f"[OK] {bin_file} - primera: offset {offset1}, length {length1}; "
                             f"segunda: offset {offset2}, length {length2}\n")

        except Exception as e:
            log_lines.append(f"[ERROR] {bin_file}: {e}\n")

    # Escribir archivo binario final
    output_bin = os.path.join(base_path, f"{base_file}.bin")
    with open(output_bin, "wb") as f:
        for section in primera_secciones:
            f.write(section)
        for section in segunda_secciones:
            f.write(section)

    total_primera = sum(len(s) for s in primera_secciones)
    total_segunda = sum(len(s) for s in segunda_secciones)

    # Escribir archivo .txt acompañante
    output_txt = os.path.join(base_path, f"{base_file}.txt")
    with open(output_txt, "w", encoding="utf-8") as f:
        f.write("1                       SPRITE FILE \n")
        f.write(formatear_linea(0, total_primera, base_file + "_s"))
        f.write(formatear_linea(total_primera, total_segunda, base_file + "_a"))

    # Guardar log detallado
    log_file = os.path.join(base_path, f"{base_file}_log.txt")
    with open(log_file, "w", encoding="utf-8") as f:
        f.writelines(log_lines)

    print(f"Generado: {output_bin}, {output_txt}, log en {log_file}")

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Uso: python script.py <ruta/nombre_base>")
        sys.exit(1)

    base_name = sys.argv[1]
    procesar_archivos(base_name)
